package com.opensource.component.extend.point.condition;

import com.opensource.component.extend.point.anntation.SpecificExtend;
import com.opensource.component.extend.point.enums.SpecificExtendFlagEnum;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/**
 * @author zhanglong and since on 2022/12/13 8:17 下午
 */
public class SpecificExtendConditional extends SpringBootCondition {


    @SneakyThrows
    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        final Environment environment =  context.getBeanFactory().getBean(Environment.class);
        final String extendFlag = environment.getProperty(SpecificExtendFlagEnum.extend_flag);
        final Field field = metadata.getClass().getDeclaredField("className");
        field.setAccessible(true);
        final String className = field.get(metadata).toString();
        final Class<?> extendBeanClass = ClassUtils.forName(className, context.getClassLoader());
        if (!StringUtils.hasText(extendFlag)) {
            return new ConditionOutcome(false, extendBeanClass.getName());
        }
        final SpecificExtendFlagEnum specificExtendFlagEnum = SpecificExtendFlagEnum.nameByEnum(extendFlag);
        final SpecificExtendFlagEnum extendFlagAnn = extendBeanClass.getAnnotation(SpecificExtend.class).extendFlag();
        return new ConditionOutcome(specificExtendFlagEnum == extendFlagAnn, extendBeanClass.getName());
    }
}
